import { Component, OnInit, inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd/message';
import { CategoryService } from '../../services/category.service';
import { Category, CreateCategoryRequest, UpdateCategoryRequest, QueryParams } from '../../models/blog.model';

@Component({
  selector: 'app-manage-blogcategory',
  standalone: false,
  templateUrl: './manage-blogcategory.component.html',
  styleUrl: './manage-blogcategory.component.less'
})
export class ManageBlogcategoryComponent implements OnInit {
  // 依赖注入
  private fb = inject(FormBuilder);
  private categoryService = inject(CategoryService);
  private message = inject(NzMessageService);

  // 数据属性
  categories: Category[] = [];
  loading = false;
  
  // 分页属性
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  
  // 搜索属性
  searchValue = '';
  
  // 模态框属性
  isModalVisible = false;
  modalTitle = '添加分类';
  editingCategory: Category | null = null;
  
  // 表单
  categoryForm: FormGroup;

  constructor() {
    this.categoryForm = this.fb.group({
      title: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(50)]],
      desc: ['', [Validators.required, Validators.minLength(1), Validators.maxLength(200)]]
    });
  }

  ngOnInit(): void {
    this.loadCategories();
  }

  /**
   * 加载分类列表
   */
  loadCategories(): void {
    this.loading = true;
    const params: QueryParams = {
      page: this.pageIndex,
      size: this.pageSize,
      q: this.searchValue || undefined
    };

    this.categoryService.getCategories(params).subscribe({
      next: (response) => {
        if (response.status && response.data) {
          this.categories = response.data.categories;
          this.total = response.data.total;
        }
        this.loading = false;
      },
      error: (error) => {
        console.error('加载分类失败:', error);
        this.message.error('加载分类失败');
        this.loading = false;
      }
    });
  }

  /**
   * 搜索分类
   */
  onSearch(): void {
    this.pageIndex = 1;
    this.loadCategories();
  }

  /**
   * 重置搜索
   */
  onSearchReset(): void {
    this.searchValue = '';
    this.pageIndex = 1;
    this.loadCategories();
  }

  /**
   * 分页变化
   */
  onPageIndexChange(pageIndex: number): void {
    this.pageIndex = pageIndex;
    this.loadCategories();
  }

  /**
   * 页面大小变化
   */
  onPageSizeChange(pageSize: number): void {
    this.pageSize = pageSize;
    this.pageIndex = 1;
    this.loadCategories();
  }

  /**
   * 显示添加模态框
   */
  showAddModal(): void {
    this.modalTitle = '添加分类';
    this.editingCategory = null;
    this.categoryForm.reset();
    this.isModalVisible = true;
  }

  /**
   * 显示编辑模态框
   */
  showEditModal(category: Category): void {
    this.modalTitle = '编辑分类';
    this.editingCategory = category;
    this.categoryForm.patchValue({
      title: category.title,
      desc: category.desc
    });
    this.isModalVisible = true;
  }

  /**
   * 关闭模态框
   */
  handleModalCancel(): void {
    this.isModalVisible = false;
    this.categoryForm.reset();
    this.editingCategory = null;
  }

  /**
   * 提交表单
   */
  handleModalOk(): void {
    if (this.categoryForm.valid) {
      const formValue = this.categoryForm.value;
      
      if (this.editingCategory) {
        // 编辑分类
        this.updateCategory(this.editingCategory._id, formValue);
      } else {
        // 添加分类
        this.createCategory(formValue);
      }
    } else {
      // 标记所有字段为已触摸，以显示验证错误
      Object.values(this.categoryForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  /**
   * 创建分类
   */
  createCategory(data: CreateCategoryRequest): void {
    this.categoryService.createCategory(data).subscribe({
      next: (response) => {
        this.message.success('分类创建成功');
        this.isModalVisible = false;
        this.categoryForm.reset();
        this.loadCategories();
      },
      error: (error) => {
        console.error('创建分类失败:', error);
        this.message.error('创建分类失败');
      }
    });
  }

  /**
   * 更新分类
   */
  updateCategory(id: string, data: UpdateCategoryRequest): void {
    this.categoryService.updateCategory(id, data).subscribe({
      next: (response) => {
        this.message.success('分类更新成功');
        this.isModalVisible = false;
        this.categoryForm.reset();
        this.editingCategory = null;
        this.loadCategories();
      },
      error: (error) => {
        console.error('更新分类失败:', error);
        this.message.error('更新分类失败');
      }
    });
  }

  /**
   * 删除分类
   */
  deleteCategory(id: string): void {
    this.categoryService.deleteCategory(id).subscribe({
      next: (response) => {
        this.message.success('分类删除成功');
        this.loadCategories();
      },
      error: (error) => {
        console.error('删除分类失败:', error);
        this.message.error('删除分类失败');
      }
    });
  }

  /**
   * 格式化日期
   */
  formatDate(dateString: string): string {
    return new Date(dateString).toLocaleDateString('zh-CN');
  }

  /**
   * 获取表单控件的错误信息
   */
  getFormControlError(controlName: string): string {
    const control = this.categoryForm.get(controlName);
    if (control && control.errors && control.dirty) {
      if (control.errors['required']) {
        return `${controlName === 'title' ? '分类名称' : '分类描述'}不能为空`;
      }
      if (control.errors['minlength']) {
        return `${controlName === 'title' ? '分类名称' : '分类描述'}长度至少为${control.errors['minlength'].requiredLength}个字符`;
      }
      if (control.errors['maxlength']) {
        return `${controlName === 'title' ? '分类名称' : '分类描述'}长度不能超过${control.errors['maxlength'].requiredLength}个字符`;
      }
    }
    return '';
  }
}
